package com.data.platform.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 拒绝策略工厂
 */
@Slf4j
public class RejectedExecutionHandlerUtils {
    private static final AtomicLong COUNTER = new AtomicLong();

    /**
     * 拒绝策略
     *
     * @param source log name
     * @return A handler for tasks that cannot be executed by ThreadPool
     */
    public static RejectedExecutionHandler newAbort(String source) {
        return (r, executor) -> {
            log.error("[{}] ThreadPool [{}] overload, the task [{}] will be abort", source, executor, r);
            throw new RejectedExecutionException("Task " + r.toString() +
                    " rejected from " + source);
        };
    }

    /**
     * 直接丢弃该任务
     *
     * @param source log name
     * @return A handler for tasks that cannot be executed by ThreadPool
     */
    public static RejectedExecutionHandler newDiscard(String source) {
        return (r, executor) -> {
            log.error("[{}] ThreadPool [{}] overload, the task [{}] will be discard", source, executor, r);
        };
    }

    /**
     * 调用线程运行
     *
     * @param source log name
     * @return A handler for tasks that cannot be executed by ThreadPool
     */
    public static RejectedExecutionHandler newCallerRuns(String source) {
        return (r, executor) -> {
            log.error("[{}] ThreadPool [{}] overload, the task [{}] will run by caller thread", source, executor, r);
            if (!executor.isShutdown()) {
                r.run();
            }
        };
    }

    /**
     * 新线程运行
     *
     * @param source log name
     * @return A handler for tasks that cannot be executed by ThreadPool
     */
    public static RejectedExecutionHandler newThreadRun(String source) {
        return (r, executor) -> {
            log.error("[{}] ThreadPool [{}] overload, the task [{}] will run by a new thread", source, executor, r);
            if (!executor.isShutdown()) {
                String threadName = source + "-thread-" + COUNTER.getAndIncrement();
                log.info("[{} create new thread [{}]] to run", source, threadName);
                new Thread(r, threadName).start();
            }
        };
    }
}
